using System;
using System.Threading;
using System.Windows.Forms;

namespace WIT.Global;

/// <summary>
/// 全局异常捕获帮助类
/// </summary>
public class ThreadExceptionHandler
{
	/// <summary>
	/// 捕获UI线程的异常
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	public void UIThreadException(object sender, ThreadExceptionEventArgs e)
	{
		try
		{
			ShowThreadExceptionDialog("UI线程异常", e.Exception);
		}
		catch
		{
			try
			{
				MessageBox.Show("严重的UI线程异常", "UI线程异常", MessageBoxButtons.OK, MessageBoxIcon.Hand);
			}
			finally
			{
				Environment.Exit(0);
			}
		}
	}

	/// <summary>
	/// 捕获非UI线程的异常
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	public void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
	{
		try
		{
			ShowThreadExceptionDialog("非UI线程异常", (Exception)e.ExceptionObject);
		}
		catch (Exception ex)
		{
			try
			{
				MessageBox.Show("严重的非UI线程异常：" + ex.Message, "非UI线程异常", MessageBoxButtons.OK, MessageBoxIcon.Hand);
			}
			finally
			{
				Environment.Exit(0);
			}
		}
	}

	/// <summary>
	/// 创建错误信息并显示
	/// </summary>
	/// <param name="title"></param>
	/// <param name="ex"></param>
	/// <returns></returns>
	private void ShowThreadExceptionDialog(string title, Exception ex)
	{
		string text = "应用程序错误，请联系管理员。\r\nException：" + ex.Message + "\r\nInnerException：" + ex.InnerException?.Message + "\r\nStackTrace：" + ex.StackTrace;
		LocalLog.Error(text);
		if (MessageBox.Show(text, title, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Hand) == DialogResult.Abort)
		{
			Environment.Exit(0);
		}
	}
}
